import axios, { type AxiosInstance, type InternalAxiosRequestConfig, type AxiosResponse } from 'axios'
import type { BaseResponse } from '@/types/common/response'
import TokenManager from './auth'
import { ElMessage } from 'element-plus'
import router from '@/router'

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api/v1',
  timeout: 15000
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 添加认证token
    const token = TokenManager.getAccessToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  <T = any>(response: AxiosResponse<BaseResponse<T>>): BaseResponse<T> => {
    const data = response.data
    // 后端返回格式: { code: 0, message: "success", data: {...} }
    // code 为 0 表示成功
    if (data.code === 0) {
      return data as BaseResponse<T>
    } else {
      // 业务错误
      ElMessage.error(data.message || '请求失败')
      return Promise.reject(new Error(data.message || '请求失败')) as any
    }
  },
  async (error) => {
    const { response } = error
    if (response) {
      const { status, data } = response
      
      // 显示后端返回的错误信息
      if (data && data.message) {
        ElMessage.error(data.message)
      } else {
        // Token过期
        if (status === 401) {
          // 尝试刷新Token
          const newToken = await TokenManager.refreshToken()
          if (newToken) {
            // 刷新成功，重新发送请求
            const config = error.config
            config.headers.Authorization = `Bearer ${newToken}`
            return service.request(config)
          } else {
            // 刷新失败，跳转到登录页
            ElMessage.error('登录已过期，请重新登录')
            router.push('/login')
          }
        } else if (status === 403) {
          ElMessage.error('权限不足')
        } else if (status >= 500) {
          ElMessage.error('服务器内部错误')
        }
      }
    } else {
      ElMessage.error('网络连接失败')
    }

    return Promise.reject(error)
  }
)

export default service
